/**
 * 
 */
package abel.wlmr.server;

import org.joda.time.DateTime;

import abel.wlmr.config.MeterStation;
import abel.wlmr.config.PacketCounter;
import abel.wlmr.config.PacketSender;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

/**
 * @author Abel
 *
 */
public final class PacketConsts {
    
    public static final AttributeKey<MeterStation> stationKey = AttributeKey.valueOf("stat");

    public static final AttributeKey<PacketSender> senderKey = AttributeKey.valueOf("sender");

    public static final AttributeKey<Byte> sequenceKey = AttributeKey.valueOf("seq");

    public static final AttributeKey<PacketCounter> counterKey = AttributeKey.valueOf("counter");

    public static final AttributeKey<DateTime> lastQueryKey = AttributeKey.valueOf("lastQuery");
    
    public static final AttributeKey<DateTime> lastConfigureKey = AttributeKey.valueOf("lastConfigure");

    public static final AttributeKey<DateTime> lastFirstTaskKey = AttributeKey.valueOf("lastFirstTask");

    public static final AttributeKey<DateTime> lastSecondTaskKey = AttributeKey.valueOf("lastSecondTask");

    public static final AttributeKey<DateTime> lastFirstDataKey = AttributeKey.valueOf("lastFirstData");

    public static final AttributeKey<DateTime> lastSecondDataKey = AttributeKey.valueOf("lastSecondData");

    /**
     * Returns the next seq.
     * 
     * @param ctx
     * @return
     */
    public static byte nextSequence(ChannelHandlerContext ctx) {
        Attribute<Byte> seq = ctx.channel().attr(sequenceKey);

        Byte cur = seq.get();

        for (int i = 0; i < 10; i++) {
            byte old = cur;
            cur = (byte) ((cur + 1) & 0x0F);

            if (seq.compareAndSet(old, cur)) {
                return cur;
            }
        }

        return cur;
    }

}
